//
//  AllOrderViewModel.m
//  GLGW_Shoping
//
//  Created by yang on 2018/11/26.
//  Copyright © 2018年 yang. All rights reserved.
//

#import "AllOrderViewModel.h"
#import "OrderListHeaderTableViewHeaderFooterView.h"
#import "OrderListFootTableViewHeaderFooterView.h"
#import "OrderFootTimeTableViewHeaderFooterView.h"
#import "OrderGoodsTableViewCell.h"
#import "OrderOperationView.h"
#import "LoginModel.h"
#import "AllOrderModel.h"
#import "BtnMoreAlertView.h"

@interface AllOrderViewModel ()<UITableViewDataSource,UITableViewDelegate>
{
    UITableView *selfTableView;
    UIView *selfView;
    NSInteger seleSection; // 取消或者点击确认某一行
    NSInteger bottomTage;  // 底部按钮记录
}
@property (nonatomic, strong) AllOrderModel *model;

@property (nonatomic, strong) BtnMoreAlertView *alerV;

@end

@implementation AllOrderViewModel

- (instancetype)initWithViewToViewModel:(UITableView *)tableView theSuperView:(UIView *)superView {
    if (self = [super initWithViewToViewModel:tableView theSuperView:superView]) {
        tableView.height = tableView.height - kHeightProportion_In_iPhoneTriploid(34);
        tableView.delegate = self;
        tableView.dataSource = self;
        tableView.rowHeight = kHeightProportion_In_iPhoneTriploid(120);
        [tableView registerClass:[OrderListHeaderTableViewHeaderFooterView class] forHeaderFooterViewReuseIdentifier:@"OrderListHeaderTableViewHeaderFooterView"];
        [tableView registerClass:[OrderListFootTableViewHeaderFooterView class] forHeaderFooterViewReuseIdentifier:@"OrderListFootTableViewHeaderFooterView"];
        [tableView registerClass:[OrderFootTimeTableViewHeaderFooterView class] forHeaderFooterViewReuseIdentifier:@"OrderFootTimeTableViewHeaderFooterView"];
        [superView addSubview:tableView];
        selfTableView = tableView;
        selfView = superView;
        [self requestOrderListData];
    }
    return self;
}

#pragma mark -- UITableViewDataSource,UITableViewDelegate
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return self.model.data.infos.count;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    
    AllOrderDetailListModel *detailListModel = self.model.data.infos[section];
    return detailListModel.orderGoods.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    OrderGoodsTableViewCell *cell = [OrderGoodsTableViewCell cellWithTableView:tableView];
    if (self.model.data.infos.count > 0) {
        AllOrderDetailListModel *detialListModel = self.model.data.infos[indexPath.section];
        [cell refreshCell:detialListModel index:indexPath];
    }
    return cell;
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
    OrderListHeaderTableViewHeaderFooterView *headerView = [tableView dequeueReusableHeaderFooterViewWithIdentifier:@"OrderListHeaderTableViewHeaderFooterView"];
    if (self.model.data.infos.count > 0) {
        AllOrderDetailListModel *detailListModel = self.model.data.infos[section];
        headerView.detailListModel = detailListModel;
    }
    return headerView;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    return kHeightProportion_In_iPhoneTriploid(50);
}

- (UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section {
    UITableViewHeaderFooterView *footView;
    kWeakSelf(self);
    if (self.model.data.infos.count > 0) {
        AllOrderDetailListModel *detailListModel = self.model.data.infos[section];
       
        if (detailListModel.orderStatus == 2) { // 待支付
            OrderFootTimeTableViewHeaderFooterView *timeFootView = [tableView dequeueReusableHeaderFooterViewWithIdentifier:@"OrderFootTimeTableViewHeaderFooterView"];
            timeFootView.section = section;
            if (self.model.data.infos.count > 0) {
                AllOrderDetailListModel *detailListModel = self.model.data.infos[section];
                timeFootView.detailListModel = detailListModel;
                timeFootView.Block_PayAction = ^(GLGWButton * _Nullable but, NSInteger section) {
                    [weakself bottomBtnClikWith:but section:section];
                };
            }
            footView = timeFootView;
        } else {
            OrderListFootTableViewHeaderFooterView *listFootView = [tableView dequeueReusableHeaderFooterViewWithIdentifier:@"OrderListFootTableViewHeaderFooterView"];
            listFootView.section = section;
            if (self.model.data.infos.count > 0) {
                AllOrderDetailListModel *detailListModel = self.model.data.infos[section];
                listFootView.detailListModel = detailListModel;
                [listFootView setBlock_BottomAction:^(GLGWButton * _Nullable but, NSInteger section) {
                    [weakself bottomBtnClikWith:but section:section];
                }];
            }
            footView = listFootView;

        }
    }
   
    return footView;
}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section {
    if (self.model.data.infos.count > 0) {
        AllOrderDetailListModel *detailListModel = self.model.data.infos[section];
        if (detailListModel.orderStatus == 2) { // 待支付
            return kHeightProportion_In_iPhoneTriploid(82);

        } else {
            return kHeightProportion_In_iPhoneTriploid(60);
        }
    }
    return 0;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    AllOrderDetailListModel *detailListModel = self.model.data.infos[indexPath.section];
    if (self.delegate && [self.delegate respondsToSelector:@selector(orderListDidSelectRowAtIndexPath:)]) {
        [self.delegate orderListDidSelectRowAtIndexPath:detailListModel];
    }
}

/*
 0, // 下载合同
 1, // 再次购买
 2, // 取消并撤回
 3, // 取消
 4, // 去支付
 5, // 确认收货
 6, // 提货单
 7  // 申请发票
 8  // 更多
 9  // 分享
 */
// 底部按钮点击事件
- (void)bottomBtnClikWith:(GLGWButton *)btn section:(NSInteger)section
{
    switch (btn.tag) {
        case 340: // 下载合同
            break;
        case 341: // 再次购买
            
            break;
        case 342: // 取消并撤回
            [self showAlertV:@"您的订单卖家正在确认，您确定\n要撤回取消订单？" strArr:@[@"撤回订单", @"取消"]];
            break;
        case 343: // 取消
            seleSection = section;
            bottomTage = 343;
            [self showAlertV:@"您正在取消订单，您确定\n要取消订单？" strArr:@[@"取消订单", @"暂不取消"]];
            break;
        case 344: // 去支付
            
            break;
        case 345: // 确认收货
            seleSection = section;
            bottomTage = 345;
            [self showAlertV:@"您的订单正在确认收货，您确定\n已经收到货了么？" strArr:@[@"确定收货", @"取消"]];
            break;
        case 346: // 提货单
            
            break;
        case 347: // 申请发票
            break;
        case 348: // 更多按钮
            [self showMoreAlertV:btn];
            break;
        case 349: // 分享
            break;
        default:
            break;
    }
    AllOrderDetailListModel *detailListModel = self.model.data.infos[section];
    if (self.BlockBttomBtnClick) {
        self.BlockBttomBtnClick(btn, detailListModel);
    }
}

- (void)showAlertV:(NSString *)str strArr:(NSArray *)arr
{
    OrderOperationView *opeartionView = [[OrderOperationView alloc] initWithPopOrderOperation:arr theTitleStr:@"操作提示" theTosStr:str];
    [opeartionView show];
    opeartionView.Block_CaseAction = ^(NSInteger tag) {
        if (tag == 310) {
            [self requestOrderStatusChange];
        }
    };
}

- (void)showMoreAlertV:(GLGWButton *)btn
{
    btn.selected = !btn.isSelected;
  
    CGRect frea = [btn convertRect:btn.bounds toView:selfView];
    CGFloat kH = kHeightProportion_In_iPhoneTriploid(61);
    CGFloat newY = frea.origin.y - kH + kHeightProportion_In_iPhoneTriploid(4);
    CGRect newF = CGRectMake(kWidthProportion_In_iPhoneTriploid(40), newY, kWidthProportion_In_iPhoneTriploid(66), kH);
    self.alerV.frame = newF;

    kWeakSelf(self);    
    OrderFootTimeTableViewHeaderFooterView *footerV = (OrderFootTimeTableViewHeaderFooterView *)btn.superview;

    _alerV.BlockBtnClick = ^(GLGWButton *btn) {
        [weakself bottomBtnClikWith:btn section:footerV.section];
    };
    if (btn.selected) {
        [self.alerV showV];
    } else {
        [self.alerV hiddenV];
    }
}

- (BtnMoreAlertView *)alerV
{
    if (!_alerV) {
        _alerV = [[BtnMoreAlertView alloc] initBtnMoreAlertView:selfView arr:@[@"取消订单", @"下载合同"] bgImgStr:@"bg_gengduo_shang"];
    }
    return _alerV;
}

- (void)scrollViewDidScroll:(UIScrollView *)scrollView
{
    [self.alerV hiddenV];
}

#pragma mark - 请求接口
- (void)requestOrderListData
{
    if (self.userInforData.length == 0) return;
    @weakify(self);
    _invoiceCommand = [[RACCommand alloc] initWithSignalBlock:^RACSignal *_Nonnull(id  _Nullable input) {
        @strongify(self);
        RACSignal *signal = [RACSignal createSignal:^RACDisposable *_Nullable(id<RACSubscriber>  _Nonnull subscriber) {
            NSMutableDictionary *param = (NSMutableDictionary *)input;
            [GLGWRequestTool POST:[NSString stringWithFormat:@"%@%@",kApiPrefix,kMyOrderList] lodingView:nil lodingTextString:@"" isLoding:YES parameters:param success:^(id  _Nullable response) {
                [subscriber sendNext:response];
                [subscriber sendCompleted];
            } failure:^(NSError *_Nullable error) {
                DLog(@"订单列表=%@",error);
                [subscriber sendNext:error];
                [subscriber sendCompleted];
            }];
            return nil;
        }];
        return [signal map:^id _Nullable(id  _Nullable value) {
            self.model = [AllOrderModel yy_modelWithJSON:value];
            [self makeOrderListData];
            DLog(@"===%@",value);
            return self.model;
        }];
    }];
}

- (void)makeOrderListData
{
    NSMutableArray *inforsArr = [NSMutableArray arrayWithArray:self.model.data.infos];
    NSMutableArray *nomarlArr = [NSMutableArray array];
    NSMutableArray *rapidArr = [NSMutableArray array];
    for (AllOrderDetailListModel *detailListModel in inforsArr) {
        if (detailListModel.tradingMode == 1) {  // 1：常规
//            detailListModel.orderStatus = 2;
            [nomarlArr addObject:detailListModel];
        } else {
//            detailListModel.orderStatus = 6;
            [rapidArr addObject:detailListModel];
        }
    }
    NSMutableArray *endArr = [NSMutableArray arrayWithArray:nomarlArr];
    [endArr addObjectsFromArray:rapidArr];
    self.model.data.infos = endArr;
    [selfTableView reloadData];
}

- (void)requestOrderStatusChange
{
    if (self.userInforData.length == 0) return;
    AllOrderDetailListModel *detailListModel = self.model.data.infos[seleSection];
    NSInteger statusNum = 6;
    if (bottomTage == 343) {
        statusNum = 19;
    }
    NSDictionary *param = @{
                          @"orderId" : koString(detailListModel.orderId),
                          @"orderStatus" : @(statusNum),  // 6：交易完成 19：订单取消 
//                          @"userId" : koString(self.userId),
                          @"userId": @"1231232",
                          @"type" : @(1)   // 1：买家：3卖家
                          };
    [GLGWRequestTool POST:[NSString stringWithFormat:@"%@%@",kApiPrefix,kMyOrderModifyorderstatus] lodingView:nil lodingTextString:@"" isLoding:YES parameters:param success:^(id  _Nullable response) {
        BaseModel *baseModel = [BaseModel yy_modelWithJSON:response];
        if ([baseModel.data isEqualToString: @"1"]) {
            [self reloadRow];
        }
    } failure:^(NSError *_Nullable error) {
        DLog(@"订单列表=%@",error);
    }];
}

- (void)reloadRow
{
    AllOrderDetailListModel *detailListModel = self.model.data.infos[seleSection];
    if (bottomTage == 343) {
        detailListModel.orderStatus = 19;
    } else if (bottomTage == 345) {
        detailListModel.orderStatus = 6;
    }
    NSIndexSet *set = [[NSIndexSet alloc] initWithIndex:seleSection];
    [selfTableView reloadSections:set withRowAnimation:UITableViewRowAnimationAutomatic];
}

@end
